<?php

namespace App\Model;

use App\Helpers\AliyunUtil;
use App\Helpers\DateUtil;
use Hyperf\DbConnection\Db;
use Illuminate\Database\Eloquent\Model;

/**
 *  通话
 */
class CallBase extends Model
{
    // protected $table = 'video_call';
    protected $fillable = [
        'user_id', 'chat_user_id', 'status', 'from', 'start_time', 'call_time', 'end_time'
    ];

    //类型
    const CALL_TYPE = -1;

    //正在呼叫
    const STATUS_NO_PICK = 0;
    //正在通话
    const STATUS_ING = 1;
    //已接听-正常挂断
    const STATUS_OK = 2;
    //已接听-异常挂断
    const STATUS_ERR_HANGUP = 3;
    //已接听-运营后台关闭
    const STATUS_ADMIN_HANGUP = 4;
    //已接听-涉黄挂断
    const STATUS_YELLOW_HANGUP = 7;
    //未接通-呼叫方挂
    const STATUS_CALLER_STOP = 5;
    //未接通-被叫方拒
    const STATUS_HOST_REJECT = 6;
    //未接通-已失效（无人接听）
    const STATUS_INVALID = -1;
    const STATUS = [
        self::STATUS_NO_PICK => '正在呼叫',
        self::STATUS_ING => '已接听-正在通话',
        self::STATUS_OK => '已接听-正常挂断',
        self::STATUS_ERR_HANGUP => '已接听-异常挂断',
        self::STATUS_ADMIN_HANGUP => '已接听-运营后台关闭',
        self::STATUS_YELLOW_HANGUP => '已接听-涉黄挂断',
        self::STATUS_INVALID => '未接通-已失效（无人接听及其他）',
        self::STATUS_CALLER_STOP => '未接通-呼叫挂',
        self::STATUS_HOST_REJECT => '未接通-被叫拒'
    ];

    //来源-新手福利
    const FROM_NEW = 1;
    //来源-一键聊天
    const FROM_QUCIK = 2;
    //来源-首页女用户
    const FROM_MAIN = 3;
    //随心聊
    const FROM_QUICK_MESSAGE = 4;
    //天天福利
    const FROM_DAILY_FREE = 5;
    //IOS
    const FROM_IOS_QUICK_MATCH = 6;
    //天天福利-主播
    const FROM_DAILY_FREE_HOST = 7;
    //女用户呼叫
    const FROM_HOST_CALL = 8;

    //邀约电话
    const FROM_INVITE_CALL = 9;

    // 特惠视频
    const FROM_DISCOUNT_CALL = 10;

    const FROM_TYPE = [
        // self::FROM_NEW => '新手福利',
        // self::FROM_QUCIK => '一键语聊',
        self::FROM_MAIN => '常规',
        self::FROM_DAILY_FREE => '天天福利',
        self::FROM_QUICK_MESSAGE => '随心聊',
        self::FROM_HOST_CALL => '女用户呼叫常规',
        self::FROM_IOS_QUICK_MATCH => 'IOS快速匹配',
        self::FROM_INVITE_CALL => '视频约会',
        self::FROM_DISCOUNT_CALL => '特惠视频',
    ];

    //成功通话的状态
    const DONE_STATUS = [self::STATUS_OK, self::STATUS_ERR_HANGUP, self::STATUS_ADMIN_HANGUP];

    public function fromUser()
    {
        return $this->belongsTo(UserProfile::class, 'user_id', 'user_id');
    }

    public function toUser()
    {
        return $this->belongsTo(UserProfile::class, 'chat_user_id', 'user_id');
    }

    public function logInfo()
    {
        return $this->belongsTo(CoinLog::class, 'order_id', 'order_id');
    }

    public function serviceFee()
    {
        return $this->belongsTo(ServiceFeeLog::class, 'order_id', 'order_id');
    }

    /**
     * 查找记录
     */
    static function checkRecord($userId = 0, $chatUserId = 0, $channelId = '')
    {
        $where = [
            'user_id' => $userId,
            'chat_user_id' => $chatUserId
        ];
        $orWhere = [
            'user_id' => $chatUserId,
            'chat_user_id' => $userId,
        ];
        if ($channelId) $where['channel_id'] = $orWhere['channel_id'] = $channelId;
        return self::where($where)->orWhere(function ($query) use ($orWhere) {
            $query->where($orWhere);
        })->orderBy('id', 'desc')->first();
    }

    /**
     * 查找记录-新手福利语聊
     */
    static function checkRecordForNew($userId = 0)
    {
        $where = [
            'user_id' => $userId,
            'from' => self::FROM_NEW
        ];
        return self::where($where)->orderBy('id', 'desc')->first();
    }

    /**
     * 获取用户最后一条拨打记录
     */
    static function checkLastRecord($userId = 0)
    {
        $where = [
            ['user_id', $userId],
        ];
        return self::where($where)->orderBy('id', 'desc')->first();
    }

    /**
     * 截止当前语聊总时间（分钟）
     */
    static function calTotalMinutes($record = [])
    {
        return ceil((time() - $record['answer_time']) / 60);
    }

    /**
     * 截止当前语聊总花费
     */
    static function calTotalCost($record = [], $coinSetting = 0)
    {
        if (!$record || !$coinSetting) return 0;
        return self::calTotalMinutes($record) * $coinSetting;
    }

    /**
     * 新手福利免费语聊当前总时间
     */
    static function totalFreeMinutes($userId = 0)
    {
        $where = [
            ['user_id', $userId],
            ['from', '=', self::FROM_NEW]
        ];
        $logs = self::where($where)->get()->toArray();
        $minutes = 0;
        foreach ($logs as $log) {
            if ($log['end_time'] && $log['call_time']) {
                $minutes += ceil($log['call_time'] / 60);
            } elseif ($log['status'] == self::STATUS_ING && $log['answer_time']) {
                $minutes += ceil((time() - $log['answer_time']) / 60);
            }
        }
        return $minutes;
    }

    /**
     * 获取当次通话的总时长
     */
    static function totalValidTime($userId = 0, $callFrom = 1, $coinSetting = 10.0)
    {
        //收费设置
        switch ($callFrom) {
                //新人福利
            case self::FROM_NEW:
                $coinSetting = 0;
                $profile = UserProfile::getProfile($userId);
                $validTime = $profile && $profile->free_call_time ? $profile->free_call_time : 0;
                break;
            default:
                // $profile = UserProfile::getProfile($chatUserId);
                // $coinSetting = $profile ? $profile->coin_setting : 9999;
                $coinInfo = UserCoin::getUserInfo($userId);
                $totalCoin = $coinInfo['total_coin'] ?? 0;
                $validTime = $coinSetting ? floor($totalCoin / $coinSetting) : 0;
                break;
        }
        return $validTime;
    }


    static function getTotalCallMinutes($userId, $chatUserId)
    {
        $where    = [];

        $userId && $where[] = ['user_id', $userId];
        $chatUserId && $where[] = ['chat_user_id', $chatUserId];

        $where[] = ['call_time', '>', 0];
        $data    = self::where($where)->whereIn('status', self::DONE_STATUS)->select(['call_time'])->get()->toArray();
        $minutes = 0;
        foreach ($data as $item) {
            $item['call_time'] > 10 && $minutes += ceil($item['call_time'] / 60);
        }
        return $minutes;
    }
}
